package cn.springboot.erp.controller;

import cn.springboot.erp.commons.QueryParams;
import cn.springboot.erp.commons.ResponseResult;
import cn.springboot.erp.entity.PurchaseOrders;
import cn.springboot.erp.service.PurchaseOrdersService;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.util.Date;

@RestController
@RequestMapping("purchaseOrder")
@Api(tags = "采购订单")
public class PurchaseOrderController {

    @Resource
    private PurchaseOrdersService purchaseOrdersService;

    @ApiOperation("数据分页")
    @PostMapping("page")
    public ResponseResult listPage(@RequestBody QueryParams<PurchaseOrders> queryParams){
        return purchaseOrdersService.listPage(queryParams);
    }

    @ApiOperation("根据id查询")
    @GetMapping("selectById/{id}")
    public ResponseResult selectById(@PathVariable("id") Integer id){
        PurchaseOrders one = purchaseOrdersService.getById(id);
        return ResponseResult.Success().data("one",one);
    }

    @ApiOperation("根据id删除")
    @GetMapping("deleteById/{id}")
    public ResponseResult deleteById(@PathVariable("id") Integer id){
        return purchaseOrdersService.deleteById(id);
    }

    @ApiOperation("修改状态")
    @GetMapping("state/{id}/{status}")
    public ResponseResult state(@PathVariable("id") Integer id,@PathVariable("status") Integer status){
        PurchaseOrders purchaseOrders = new PurchaseOrders();
        purchaseOrders.setId(id);
        purchaseOrders.setStatus(status);
        purchaseOrdersService.updateById(purchaseOrders);
        return ResponseResult.Success().msg("状态修改成功");
    }

    @ApiOperation("添加或编辑")
    @PostMapping("insertOrUpdate")
    public ResponseResult insertOrUpdate(@RequestBody PurchaseOrders purchaseOrders){
        Date date1 = purchaseOrders.getOrderDate();
        Date date = new Date();
        LocalDate orderDate = LocalDate.of(date1.getYear(), date1.getMonth(), date1.getDay());
        System.out.println("orderDate = " + orderDate);
        LocalDate newDate = LocalDate.of(date.getYear(), date.getMonth(), date.getDay());
        System.out.println("newDate = " + newDate);
        if (orderDate.isBefore(newDate)){
            return ResponseResult.Fail().msg("采购日期不能晚于当前日期");
        }

        if (ObjectUtils.isNotNull(purchaseOrders.getId())){
            purchaseOrdersService.saveOrUpdate(purchaseOrders);
            return ResponseResult.Success().msg("修改成功");
        }
        purchaseOrdersService.saveOrUpdate(purchaseOrders);
        return ResponseResult.Success().msg("添加成功");
    }
}
